package cn.qianxun.meta.user.provider;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.qianxun.meta.common.core.utils.StreamUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.qianxun.meta.common.mybatis.helper.DataBaseHelper;
import cn.qianxun.meta.datascope.api.feign.ISysUserDataScopeProvider;
import cn.qianxun.meta.dept.entity.SysDept;
import cn.qianxun.meta.dept.mapper.SysDeptMapper;
import cn.qianxun.meta.role.entity.SysRoleDept;
import cn.qianxun.meta.role.mapper.SysRoleDeptMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Copyright:版权所有(c)qianxun
 *
 * @Author fuzhilin
 * @Description //TODO
 * @Date 2023/8/21 18:07
 **/
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SysUserDataScopeProvider implements ISysUserDataScopeProvider {


    private final SysRoleDeptMapper roleDeptMapper;
    private final SysDeptMapper deptMapper;

    @Override
    public String getRoleCustom(Long roleId) {
        List<SysRoleDept> list = roleDeptMapper.selectList(
                new LambdaQueryWrapper<SysRoleDept>()
                        .select(SysRoleDept::getDeptId)
                        .eq(SysRoleDept::getRoleId, roleId));
        if (CollUtil.isNotEmpty(list)) {
            return StreamUtils.join(list, rd -> Convert.toStr(rd.getDeptId()));
        }
        return null;
    }

    @Override
    public String getDeptAndChild(Long deptId) {
        List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptId)
                .apply(DataBaseHelper.findInSet(deptId, "ancestors")));
        List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
        ids.add(deptId);
        List<SysDept> list = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptId)
                .in(SysDept::getDeptId, ids));
        if (CollUtil.isNotEmpty(list)) {
            return StreamUtils.join(list, d -> Convert.toStr(d.getDeptId()));
        }
        return null;
    }
}
